package com.kuyun.base.realm;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.kuyun.base.model.BaseUser;
import com.kuyun.base.service.BaseUserService;
import com.kuyun.base.util.Constants;

/**
 * shrio权限管理的relm
 * 
 * @author 唐靖
 *
 * @date 2016年7月14日下午6:38:35
 *
 */
public class MyRealm extends AuthorizingRealm {

	/**
	 * 用户信息操作
	 */
	@Resource
	private BaseUserService baseUserService;

	/**
	 * 登录成功后用来设置用户角色和权限
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年3月20日下午6:34:40
	 *
	 * @param principals
	 * @return
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		BaseUser user = (BaseUser) principals.getPrimaryPrincipal();
		authorizationInfo.setStringPermissions(baseUserService.getAllPerByUserName(user)); // 本系统只通过权限来关联
		
		// authorizationInfo.setRoles(baseUserService.getAllRoleByUserLogInName(userName));
		
		return authorizationInfo;
	}

	/**
	 * 登录时调用-
	 * 
	 * @author 唐靖
	 *
	 * @date 2016年3月20日下午6:34:32
	 *
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		BaseUser user = baseUserService.findUserByLogInName(userName);
		if (user != null) {
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user, user.getPassword(),
					"login"); // 最后一个参数没有意义，忽略
			return authcInfo;
		} else {
			return null;
		}
	}

	/** 清除用户的权限缓存信息 */
	protected void doClearCache(PrincipalCollection principalcollection) {
		getAuthorizationCache().clear();
	}
	/**退出登录时清空个人缓存**/
	public void doLogOutClearCache(PrincipalCollection previousPrincipals) {
		getAuthorizationCache().remove(previousPrincipals);
	}
}
